package lumis.service.wsrp.consumer.producermanager;

import lumis.portal.PortalContext;
import lumis.portal.PortalException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.serviceinstance.ServiceInstanceConfig;
import lumis.portal.transaction.ITransaction;
import lumis.portal.transaction.PortalTransactionFactory;

import com.sun.portal.wsrp.common.stubs.v2.RegistrationData;

/**
 *	Constructs the default Registration Data given the service instance id.
 *
 *	@version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
 *	@since 6.0.0
 */
class DefaultRegistrationDataBuilder
{
	static RegistrationData initDefaultRegistrationData(String serviceInstanceId) throws PortalException
	{
		String consumerName = buildConsumerName(serviceInstanceId);
		String consumerAgent = buildConsumerAgent();
		
		RegistrationData registrationData = new RegistrationData();
		registrationData.setConsumerAgent(consumerAgent);
		registrationData.setConsumerName(consumerName);
		
		return registrationData;
	}
	
	/**
	 * Builds the consumerAgent.
	 * @return	a string representing the consumerAgent.
	 * @throws PortalException
	 */
	static private String buildConsumerAgent()	throws PortalException
	{
		return "Lumis Portal " + PortalContext.getMajorVersion() + "." + PortalContext.getMinorVersion();
	}
	
	/**
	 * Builds the consumerName: framework url + channel path + service instance
	 * name + service instance id.
	 * @return	a string representing the consumerName.
	 * @throws PortalException
	 */
	static private String buildConsumerName(String serviceInstanceId) throws PortalException
	{
		String frameworkUrl = PortalContext.getFrameworkUrl();
		ITransaction transaction = PortalTransactionFactory.createTransaction();
		try
		{
			transaction.begin();
			
			ServiceInstanceConfig sic = ManagerFactory.getServiceInstanceManager().get(serviceInstanceId, transaction);
			String serviceInstanceName = sic.getName();
			
			String channelPath = ManagerFactory.getChannelManager().getFriendlyPath(SessionConfig.getCurrentSessionConfig(), sic.getChannelId(), transaction);
			
			transaction.commit();
			
			return frameworkUrl + " " + channelPath + " " + serviceInstanceName + " " + serviceInstanceId;
		}
		finally
		{
			transaction.dispose();
		}
	}
}